package com.shjn.squirrel.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;

/**
 * listView通用适配器
 */
public class GenerateAdapter<T> extends BaseAdapter {

    private Context mContext;
    private int mLayoutResource;
    private ArrayList<T> mItems;
    private OnInitView mInitView;

    public interface OnInitView {
        void initView(View view, Object item);
    }

    public GenerateAdapter() {
    }

    public GenerateAdapter(Context context, int layoutResource,
                           ArrayList<T> items, OnInitView initView) {
        this.mContext = context;
        this.mLayoutResource = layoutResource;
        this.mItems = items;
        this.mInitView = initView;
    }

    /**
     * 插入数据
     *
     * @param item 数据项
     */
    public void inserItem(T item) {
        this.mItems.add(item);
        notifyDataSetChanged();
    }

    /**
     * 删除最后一项
     */
    public void deleteItem() {
        if (this.mItems.size() > 0) {
            this.mItems.remove(this.mItems.size() - 1);
            notifyDataSetChanged();
        }
    }

    @Override
    public int getCount() {
        return mItems.size();
    }

    @Override
    public Object getItem(int position) {
        return mItems.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public boolean isEnabled(int position) {
        return true;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = (convertView != null) ? convertView : View.inflate(mContext, mLayoutResource, null);
        if (mInitView != null) {
            mInitView.initView(view, getItem(position));
        }
        return view;
    }

}
